// import store from "../store"
import env from "@/env"
import { router } from "@/router"
import store from "@/store/index.js"

const baseUrl = env.BASE_URL
const authUrl = env.AUTH_URL

/**
 * 统一网络请求
 * 会对各个环境的返回结果做好相关的错误和返回结果处理
 * @param {Object} data 请求相关数据
 * @param {Boolean} data.upload 是否启用上传
 * @param {Boolean} data.standard 是否预处理标准的返回结果数据
 * @param {Boolean} re 是否启用免登
 */
const request = (data, re = true) => {
	// 获取到token后请求头中携带token
	const httpHeader = {
		"Content-Type": 'application/json',
		"Authorization": store.getters.token,
	}
	
	if (data.upload) {
		httpHeader["Content-Type"] = "multipart/form-data"
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: baseUrl + data.url,
				filePath: data.filePath,
				name: data.name,
				header: httpHeader,
				timeout: 15000,
				success: function(res) {
					// console.log("res", res)
					if (res.statusCode == "200") {
						const data = JSON.parse(res.data)
						// console.log("data", data)
						if (data.code === 200) {
							resolve(data)
						} else {
							uni.showToast({
								title: data.msg || '数据有误',
								icon: 'none'
							})
							reject(res.data)
						}
					} else {
						uni.showToast({
							title: 'status error!' + res.statusCode,
							icon: 'none'
						})
					}
				},
				fail: (err) => {
					console.log('err', err)
					reject({
						data: err,
						errMsg: '上传失败'
					});
					uni.showToast({
						title: "上传失败",
						icon: 'none'
					})
				}
			})
		})
	}
	
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + data.url,
			method: data.method || 'GET',
			timeout: 8000,
			header: httpHeader,
			data: data.params,
			success: res => {
				if (res.statusCode === 200) {
					if (data.standard) {
						if (res.data.code === 200) {
							resolve(res.data.data)
						} else {
							uni.showToast({
								title: res.data.msg || '数据有误',
								icon: 'none'
							})
							reject(res.data)
						}
					} else {
						if (res.data.code !== 200) {
							// 非正常返回
							if (res.data.code === 401) {
								if (re) {
									uni.showLoading({
										title: "自动登录中"
									})
									store.dispatch("fastlogin")
										.then(() => {
											uni.hideLoading()
											request(data, false)
												.then((res) => resolve(res))
												.catch((err) => reject(err))
										})
										.catch((err) => {
											uni.hideLoading()
											uni.showToast({
												title: "自动登陆失败，请手动登录",
												icon: 'none'
											})
											router.replaceAll("/pages/user/login")
											reject(err)
										})
								} else {
									// 获取到错误的TOKEN
									uni.showToast({
										title: "自动登陆失败 错误的TOKEN",
										icon: 'none'
									})
									router.push("/pages/user/login")
									reject()
								}
							} else {
								uni.showToast({
									title: res.data.msg || "未知的CODE" + res.data.code,
									icon: 'none'
								})
								// router.replace("/pages/index/server_error")
								reject(res.data)
							}
						} else {
							// 返回成功
							resolve(res.data)
						}
					}
				} else {
					// console.log("请求错误:", res)
					if (process.env.NODE_ENV === 'development') {
						if (res.data && typeof res.data === 'string') {
							uni.showToast({
								title: res.data,
								icon: 'none'
							})
						} else {
							uni.showToast({
								title: 'StatusCode错误url:' + data.url,
								icon: 'none'
							})
						}
					} else {
						if (typeof res.data === 'string') {
							uni.showToast({
								title: res,
								icon: 'none'
							})
						} else if (typeof res.data.msg === 'string') {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
						} else {
							uni.showToast({
								title: "网络错误",
								icon: 'none'
							})
						}
					}
					reject({
						data: res.data,
						errMsg: 'errStatusCode' + res.statusCode
					})
				}
			},
			fail: err => {
				console.log('err', err)
				reject({
					data: err,
					errMsg: '请求失败'
				});
				uni.showToast({
					title: '请求失败' + data.url,
					icon: 'none'
				})
				router.replace("/pages/index/net_error")
			}
		})
	})
}

export default request
